import json
import os
from django.http import HttpResponse

from User.models import User

def sign(request):#curl -H "Content-Type: application/json" -X POST -d '{ "password":"123", "email":"2506564278@qq.com"}'  "http://192.168.3.86/user/sign/"
    if request.method == "POST":
        body = json.loads(request.body)
        if len(User.objects.filter(email=body["email"])) != 0:
            return HttpResponse("用户已存在")
        if "email" in body and "password" in body:
            User.objects.create(
                email=body["email"],
                password=body["password"]
            ).save()
            if len(User.objects.filter(email=body["email"])) != 0:
                return HttpResponse("创建成功")
            else:
                return HttpResponse("创建失败")
        else:
            return HttpResponse("参数不全")
    else:
        return HttpResponse("请使用POST")

def verify(request):#http://192.168.3.86/user/verify/?email=2506564278@qq.com&password=123
    if request.method == 'GET':
        user = User.objects.filter(email=request.GET.get("email"), password=request.GET.get("password"))
        if len(user) != 0:
            return HttpResponse("验证成功")
        else:
            return HttpResponse("验证失败")
def changePassword(request):
    u=User.objects.filter(email=request.GET.get("email"))
    if len(u) != 0:
        u.update(password=request.GET.get("password"))
        return HttpResponse("修改成功")
    else:
        return HttpResponse("该用户未注册")

def updateIcon(request):
    u = User.objects.filter(email=request.GET.get("email"))
    if len(u) != 0:
        iconFile = request.FILES.get('file', None)
        print(request.FILES)
        if not iconFile:
            return HttpResponse("上传文件未找到")
        destination = open(os.path.join("files/icon", request.GET.get("email")+".png"), "wb+")
        for chunk in iconFile.chunks():
            destination.write(chunk)
        destination.close()
        return HttpResponse("上传完成")
    else:
        return HttpResponse("该用户未注册")

def updateNickname(request):
    u = User.objects.filter(email=request.GET.get("email"))
    if len(u) != 0:
        u.update(nickname=request.GET.get("nickname"))
        return HttpResponse("修改完成")
    else:
        return HttpResponse("该用户未注册")

def getNickname(request):
    u = User.objects.filter(email=request.GET.get("email"))
    if len(u) != 0:
        return HttpResponse(u[0].nickname)
    else:
        return HttpResponse("该用户未注册")